package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RedisConstants.*;
import com.hmdp.utils.RedisData;
import com.hmdp.utils.RedisUtils;
import com.hmdp.utils.SystemConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.*;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Autowired
    private StringRedisTemplate redisTemplate;


    @Resource
    private ShopMapper shopMapper;

    @Autowired
    private RedisUtils redisUtils;


    //TODO:互斥锁 和 逻辑过期没有通过压力测试过
    @Override
    public Result queryShopById(Long id) {
        /**
         * 解决缓存穿透，缓存空对象
         * Shop shop = redisUtils.queryWithPassThrough("shop:cache:", id, Shop.class, this::getById, 30L, TimeUnit.MINUTES);
         * 使用互斥锁解决缓存击穿(包含缓存穿透)
         * Shop shop = queryWithMutex(id);
         */
        //使用逻辑过期解决缓存击穿问题(不存在缓存穿透问题)  TODO:真的不存在缓存穿透问题吗？
        Shop shop = redisUtils.queryWithLogicalExpire("shop:cache:", id, Shop.class, this::getById, 30L, TimeUnit.MINUTES);
        if(Objects.isNull(shop)){
            return Result.fail("店铺不存在！");
        }
        return Result.ok(shop);
    }

    private boolean tryLock(String key){
        Boolean lock = redisTemplate.opsForValue().setIfAbsent(key, "lock", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(lock);
    }

    private void unLock(String key){
        redisTemplate.delete(key);
    }

    private Shop queryWithMutex(Long id){
        //查询缓存
        String shopJson = redisTemplate.opsForValue().get("shop:cache:" + id);
        if(StrUtil.isNotBlank(shopJson)){
            return JSONUtil.toBean(shopJson, Shop.class);
        }
        if(!Objects.isNull(shopJson)){
            return null;//避免缓存穿透
        }
        String lockKey = "lock:shop:"+id;
        Shop shop = null;
        try{

            if(!tryLock(lockKey)){
                Thread.sleep(50);
                return queryWithMutex(id);
            }
            //Double Check获取锁成功，应该再次检测redis，缓存是否存在，如果存在就无需重建。
            shopJson = redisTemplate.opsForValue().get("shop:cache:" + id);
            if(StrUtil.isNotBlank(shopJson)){
                return JSONUtil.toBean(shopJson, Shop.class);
            }
            if(!Objects.isNull(shopJson)){
                return null;
            }
            //获取到了锁，就重建缓存
            //缓存中不存在
            shop = getById(id);
            //模拟延迟
            Thread.sleep(200);
            if(Objects.isNull(shop)){
                //数据库中不存在 ===》 缓存空对象
                redisTemplate.opsForValue().set("shop:cache:" + id,"");
                return null;
            }
            //数据库中存在
            String jsonStr = JSONUtil.toJsonStr(shop);
            //存入缓存
            redisTemplate.opsForValue().set("shop:cache:" + id,jsonStr,30L, TimeUnit.MINUTES);
        }catch (Exception e){
            throw new RuntimeException(e);
        }finally {
            //释放互斥锁
            unLock(lockKey);
        }
        //返回
        return shop;
    }


    @Override
    @Transactional
    public Result updateShop(Shop shop) {
        Long shopId = shop.getId();
        if(Objects.isNull(shopId)){
            return Result.fail("Id不能为NULL");
        }
        //先更新数据库
        updateById(shop);
        //再删除缓存
        redisTemplate.delete("shop:cache:" + shopId);
        return Result.ok();
    }

    /**
     *
     * @param typeId     店铺类型Id
     * @param current   当前页数
     * @param x         坐标x
     * @param y         坐标y
     * @return  返回 shop 以及 距离，Shop类中有distance属性。
     */
    @Override
    public Result queryShopByType(Integer typeId, Integer current, Double x, Double y) {
        String key = "shop:geo:"+typeId;
        //计算分页参数
        int from  = (current - 1) * SystemConstants.DEFAULT_PAGE_SIZE;
        int end = current * SystemConstants.DEFAULT_PAGE_SIZE;
        GeoResults<RedisGeoCommands.GeoLocation<String>> results = redisTemplate.opsForGeo()
                .radius(
                        key,                                                  //键
                        new Circle(
                                new Point(x, y), new Distance(5000)     //坐标 以及 距离
                        ),
                        RedisGeoCommands.GeoRadiusCommandArgs.newGeoRadiusArgs()    //其他参数
                                .includeDistance() //返回结果包含距离
                                .limit(end));
        if(Objects.isNull(results)){
            return Result.ok();
        }
        //解析数据
        List<Long> ids = new ArrayList<>();
        Map<Long,Distance> distanceMap = new HashMap<>();
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> content = results.getContent();
        content.stream().skip(from).forEach(geoLocationGeoResult -> {
            String shopIdStr = geoLocationGeoResult.getContent().getName();
            Long shopId = Long.valueOf(shopIdStr);
            Distance distance = geoLocationGeoResult.getDistance();
            ids.add(shopId);
            distanceMap.put(shopId,distance);
        });
        if(ids.size()==0){
            return Result.ok();
        }
        //根据ids查出Shop
        List<Shop> shops = shopMapper.queryByIds(ids);
        shops.forEach(shop ->shop.setDistance(distanceMap.get(shop.getId()).getValue()));
        return Result.ok(shops);
    }
}
